package com.itheima.health.service.impl;

import com.alibaba.dubbo.common.json.JSON;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.common.RedisConst;
import com.itheima.health.dao.CheckGroupDao;
import com.itheima.health.dao.CheckItemDao;
import com.itheima.health.dao.SetmealDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.CheckGroup;
import com.itheima.health.pojo.CheckItem;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.*;

/**
 * @Author likepei
 * @Date 2020/2/10 9:42
 * @Version v1.0
 * @Description 套餐的服务接口实现类
 */
@Service
@Transactional
@Slf4j
public class SetmealServiceImpl implements SetmealService {

    //依赖注入
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private CheckGroupDao checkGroupDao;
    @Autowired
    private CheckItemDao checkItemDao;

    //依赖注入 Redis连接池对象
    @Autowired
    private JedisPool jedisPool;

    /**
     * 套餐的分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        //使用PageHelper, 设置分页查询初始信息( 当前页码, 每页条数 )
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //调用dao, 获取到满足条件(queryString)的 套餐信息
        Page<Setmeal> page = setmealDao.selectByCondition(queryPageBean.getQueryString());
        //封装PageResult对象, 并返回
        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
        return pageResult;
    }

    /**
     * 新增套餐
     * @param setmeal 前端发来的新增套餐的表单数据
     * @param checkgroupIds 前端发来的套餐所勾选的检查组ID
     */
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //保存套餐
        setmealDao.add(setmeal);
        //保存套餐与检查组的关系 (操作中间表)
        for (Integer checkgroupId : checkgroupIds) {
            //封装Map集合
            Map<String, Integer> map = new HashMap<>();
            map.put("setmeal_id", setmeal.getId());
            map.put("checkgroup_id", checkgroupId);
            //调用dao方法, 把套餐ID与勾选的检查组Id 存入中间表(t_setmeal_checkgroup)
            setmealDao.addSetmealAndCheckGroup(map);
        }

        //增加一步, 把存到到mysql数据库中的图片名称, 在redis数据库集合 setmealPicResources中删除
        Jedis jedis = jedisPool.getResource();
        /**
         * 参数一: Redis中  setmealPicResources 集合
         * 参数二: 向setmealPicResourcesset 删除的数据(图片的名称 )
         */
        jedis.srem(RedisConst.SETMEAL_PIC_RESOURCES, setmeal.getImg());
    }

    /**
     * 获取所有套餐
     * @return
     */
    @Override
    public List findAll() {
        //调用dao, 获取所有的套餐信息
        Jedis jedis = jedisPool.getResource();
        jedis.select(1);
        Set<String> keys = jedis.keys("health_setmeal_*");
        if (keys.size()==0){
            List<Setmeal> list= setmealDao.findAll();
            if (list!=null){
                for (Setmeal setmeal : list) {
                    String key="health_setmeal_"+setmeal.getId();
                    jedis.hset(key,"id",setmeal.getId()+"");
                    jedis.hset(key,"code",setmeal.getCode()+"");
                    jedis.hset(key,"helpCode",setmeal.getHelpCode()+"");
                    jedis.hset(key,"sex",setmeal.getSex()+"");
                    jedis.hset(key,"age",setmeal.getAge()+"");
                    jedis.hset(key,"price",setmeal.getPrice().toString()+"");
                    jedis.hset(key,"remark",setmeal.getRemark()+"");
                    jedis.hset(key,"attention",setmeal.getAttention()+"");
                    jedis.hset(key,"img",setmeal.getImg()+"");
                    //设置过期时间为5min
                    jedis.expire(key,60*5);
                }
                return list;
            }else {
                return null;
            }
        }
        //遍历keys集合
        //keys = jedis.keys("setmeal_*");
        //使用linkedList保证和数据库中的顺序一样
        LinkedList<Map<String, String>> resultList=new LinkedList<>();
        for (String key : keys) {
            Map<String,String> setmealFromRedis = jedis.hgetAll(key);
             resultList.addFirst(setmealFromRedis);
            System.out.println(setmealFromRedis);
        }
        return resultList;
        //return setmealDao.findAll();
    }

    /**
     * 基于套餐Id 获取指定的套餐对象
     * @param id 套餐Id
     * @return
     */
    @Override
    public String findById(Integer id) {
        /*
        //调用dao, 基于套餐Id 获取指定的套餐对象
        Setmeal setmeal =  setmealDao.findById(id);
        //调用dao, 基于套餐ID, 获取对应所关联的所有检查组信息
        List<CheckGroup> checkGroupList = checkGroupDao.findCheckGroupById(setmeal.getId());
        setmeal.setCheckGroups(checkGroupList);

        //调用dao, 基于检查组id, 获取对应所关联的所有检查项信息
        for (CheckGroup checkGroup : checkGroupList) {
            //基于检查组id, 获取对应所关联的所有检查项信息
            List<CheckItem> checkItemList = checkItemDao.findCheckItemById(checkGroup.getId());
            checkGroup.setCheckItems(checkItemList);
        }

        return setmeal;

        */

        //redis缓存数据
        Jedis jedis = jedisPool.getResource();
        //先从redis中查询
        jedis.select(2);
        String setmealFromRedis = jedis.get("health_setmealDetail_" + id);
        if (setmealFromRedis!=null){
            return setmealFromRedis;
        }
        Setmeal setmealFromDB =  setmealDao.findById(id);
        if (setmealFromDB==null){
            return null;
        }
        List<CheckGroup> checkGroupList = checkGroupDao.findCheckGroupById(setmealFromDB.getId());
        //调用dao, 基于检查组id, 获取对应所关联的所有检查项信息
        for (CheckGroup checkGroup : checkGroupList) {
            //基于检查组id, 获取对应所关联的所有检查项信息
            List<CheckItem> checkItemList = checkItemDao.findCheckItemById(checkGroup.getId());
            checkGroup.setCheckItems(checkItemList);
        }
        setmealFromDB.setCheckGroups(checkGroupList);
        try {
            String json = JSON.json(setmealFromDB);
            System.out.println(json);
            jedis.set("health_setmealDetail_" + id,json);
            //设置存活时间为5min
            jedis.expire("health_setmealDetail_" + id,5*60);
            return json;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }


    }
}
